package com.aauedu.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
public class RequestController {

    @RequestMapping("/login")
    public String login(HttpServletRequest request) {
        request.setAttribute("username", "鲍宪立");  //向request域中添加的数据
        request.getSession().setAttribute("age", "24");  //向session域中添加的数据
        return "forward:/ok";  //转发到 /ok
    }

    @RequestMapping("/ok")
    @ResponseBody
    public String ok(@RequestAttribute(value = "username", required = false) String username, @SessionAttribute(value = "age", required = false) String age, HttpServletRequest request) {
        //获取到request域中的数据
        System.out.println("username->" + username);
        System.out.println("通过原生的servlet api获取username->" + request.getAttribute("username"));
        System.out.println("age->" + age);
        System.out.println("通过原生的servlet api获取age->" + request.getSession().getAttribute("age"));
        return "success";
    }

    //响应一个注册请求
    @GetMapping("/register")
    public String register(Map<String, String> map,
                           Model model,
                           HttpServletResponse response) {
        //如果一个注册请求，会将注册数据封窗到map或model
        //map中的数据和model的数据，会被放入到request域中
        map.put("user", "hsp");
        map.put("job", "java架构师");
        model.addAttribute("sal", 80000);
        //演示创建cookie，并通过response添加到浏览器/客户端
        Cookie cookie = new Cookie("email", "123456@qq.com");
        response.addCookie(cookie);
        //请求转发
        return "forward:/registerOk";
    }

    @ResponseBody
    @GetMapping("/registerOk")
    public String registerOk(HttpServletRequest request) {
        System.out.println("user-" + request.getAttribute("user"));
        System.out.println("job-" + request.getAttribute("job"));
        System.out.println("sal-" + request.getAttribute("sal"));
        return "success";
    }
}
